<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot-scope="scope" slot="menu">
        <el-button
          v-if="permission.store_view && scope.row.isBind == '1'"
          icon="el-icon-cpu"
          size="small"
          type="text"
          @click.stop="handleDevice(scope.row, scope.index)"
          >设备管理</el-button
        >
      </template>
      <template slot="menuLeft">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          v-if="permission.store_add"
          @click="handleStorage"
          >入 库
        </el-button>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-sort-up"
          v-if="permission.store_add"
          @click="handleAllot"
          >调 拨
        </el-button>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-sort-down"
          v-if="permission.store_add"
          @click="handleRebate"
          >回 拨
        </el-button>
        <!-- <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.store_delete"
          @click="handleDelete"
          >删 除
        </el-button> -->
      </template>
      <!-- <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.store_import"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permission.store_export"
          @click="handleExport"
          >导出
        </el-button>
      </template> -->
      <template slot-scope="{row}"
            slot="isBind">
        <el-tag type="success" :color="getColor(row.isBind)" effect="dark">{{ row.isBindName }}</el-tag>
      </template>
      <template slot-scope="{row}" slot="amount">
        <el-tag type="success" :color="getColorStatus(row.amount)" effect="dark">{{ row.amountName }}</el-tag>
      </template>
      <template slot-scope="{}" slot="serviceNoSearch">
        <select-page ref="searchSerSelect" label="serviceName" value="serviceNo" :select.sync="search.serviceNo" :url="website.searchLink.serviceUrl" placeholder-text="服务商" filter-key="searchParam"></select-page>
      </template>
      <template slot-scope="{}" slot="orgNoSearch">
        <select-page ref="searchOrgSelect" label="serviceName" value="serviceNo" :select.sync="search.orgNo" :url="website.searchLink.orgUrl" placeholder-text="所属机构" filter-key="searchParam"></select-page>
      </template>
      <template slot-scope="{}" slot="rpiNoSearch">
        <select-page ref="searchRpiSelect" label="rpiName" value="rpiNo" :select.sync="search.rpiNo" :url="website.searchLink.merchantUrl" placeholder-text="商户" filter-key="searchParam"></select-page>
      </template>
    </avue-crud>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  // getDetail,
  add,
  // update,
  remove,
  selectSupList,
  selectModelList
} from "@/api/rb-oem/store/store";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import selectPage from "@/components/select-page/select-page";

var serviceDic = [{
  label:'包含下级',
  value: 1
}]
export default {
  components: {
    selectPage,
  },
  props: {
    rptNo: {
      type: String,
      required: '',
    }
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(100vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        searchIndex: 3, //从第三个后隐藏 searchIcon
        searchIcon: true, //显示搜索 展开/隐藏按钮
        menuWidth: 140,
        selection: false,
        searchMenuSpan: 6,
        columnBtn: false,
        column: [
          {
            label: "主键",
            prop: "id",
            type: "input",
            sortable: true,
            display: false,
            hide: true,
          },
          {
            label: "服务商编号",
            searchLabel: "服务商",
            prop: "serviceNo",
            type: 'select',
            search: true,
            hide: true,
            width: 110,
            searchOrder: 1,
            rules: [
              {
                required: true,
                message: "请输入服务商编号",
                trigger: "blur",
              },
            ],
          },
          {
            label: "服务商编号",
            prop: "rsServiceNo",
            type: "input",
            minWidth: 110,
            overHidden:true,
            rules: [
              {
                required: true,
                message: "请输入服务商编号",
                trigger: "blur",
              },
            ],
          },
          {
            label: "服务商名称",
            prop: "rsServiceName",
            type: "input",
            minWidth: 250,
            overHidden:true,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入服务商名称",
                trigger: "blur",
              },
            ],
          },
          // {
          //   label: "服务商编号",
          //   prop: "rsServiceNo",
          //   type: "input",
          //   width: 100,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入服务商编号",
          //       trigger: "blur",
          //     },
          //   ],
          // },
          // {
          //   label: "服务商名称",
          //   prop: "rsServiceName",
          //   type: "input",
          //   width: 100,
          //   display: false,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入服务商名称",
          //       trigger: "blur",
          //     },
          //   ],
          //   overHidden: true,
          // },
          {
            label: '',
            prop: 'isAllSer',
            type: 'select',
            multiple: false,
            dataType: "string",
            showColumn: false,
            hide: true,
            search: true,
            searchOrder: 2,
            searchType:"checkbox",
            searchSpan: 0,
            searchLabelWidth: '0',
            dicData: serviceDic
          },
          {
            label: "所属机构",
            prop: "orgNo",
            type: "select",
            showColumn: false,
            search: true,
            searchOrder: 3,
            filterable: true,
            hide: true,
            rules: [
              {
                required: true,
                message: "请选择所属机构",
                trigger: "blur",
              },
            ],
          },
          {
            label: "设备归属",
            prop: "belongTo",
            type: "select",
            search: true,
            searchOrder: 13,
            hide: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=belong_to",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请选择设备归属",
                trigger: "blur",
              },
            ],
          },
          {
            label: "设备归属",
            prop: "belongToName",
            type: "input",
            rules: [
              {
                required: true,
                message: "请输入设备归属",
                trigger: "blur",
              },
            ],
          },
          {
            label: "产品类型",
            prop: "productTypeName",
            type: "select",
            search: true,
            searchOrder: 4,
            hide: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=product_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请输入产品类型",
                trigger: "blur",
              },
            ],
          },
          {
            label: "设备类型",
            prop: "rptNo",
            type: "select",
            search: true,
            searchOrder: 5,
            hide: true,
            dicUrl: "/api/rb-oem/oem/store/store/selectTypeList?current=-1&size=-1",
            props: {
              label: "rptName",
              value: "rptNo",
              desc: "rptNo"
            },
            change: (row) => {
              if (row.value) {
                // 获取供应商
                this.form.rpsNo = '';
                this.form.rpmNo = '';
                this.form.rptNo = row.value;
                this.search.rpsNo = '';
                this.search.rpmNo = '';
                selectSupList(-1,-1,{rptNo:row.value}).then((res)=>{
                  const column = this.findObject(this.option.column, "rpsNo");
                  column.dicData = res.data.data;
                })
              }
            },
            rules: [
              {
                required: true,
                message: "请选择设备类型",
                trigger: "blur",
              },
            ],
          },
          {
            label: "设备类型",
            prop: "rptName",
            type: "input",
            rules: [
              {
                required: true,
                message: "请输入设备类型",
                trigger: "blur",
              },
            ],
          },
          {
            label: "设备品牌",
            prop: "rpsNo",
            type: "select",
            search: true,
            searchOrder: 6,
            hide: true,
            dicData: [],
            // dicUrl: "/api/rb-oem/oem/store/store/selectSupList?current=-1&size=-1&rptNo={{key}}",
            props: {
              label: "rpsName",
              value: "rpsNo",
              desc: "rpsNo"
            },
            change: (row) => {
              if (row.value && this.form.rptNo) {
                // 获取供应商
                this.form.rpsNo = '';
                this.form.rpmNo = '';
                this.search.rpsNo = '';
                this.search.rpmNo = '';
                selectModelList(-1,-1,{rpsNo:row.value,rptNo:this.form.rptNo}).then((res)=>{
                  const column = this.findObject(this.option.column, "rpmNo");
                  column.dicData = res.data.data;
                })
              }
            },
            rules: [
              {
                required: true,
                message: "请选择设备品牌",
                trigger: "blur",
              },
            ],
          },
          {
            label: "设备品牌",
            prop: "rpsName",
            type: "input",
            width: '100%',
            rules: [
              {
                required: true,
                message: "请输入设备品牌",
                trigger: "blur",
              },
            ],
          },
          {
            label: "设备型号",
            prop: "rpmNo",
            type: "select",
            search: true,
            searchOrder: 9,
            hide: true,
            dicData: [],
            // dicUrl: "/api/rb-oem/oem/store/store/selectModelList?current=-1&size=-1&rptNo={{key}}&rpsNo={{key}}",
            props: {
              label: "rpmName",
              value: "rpmNo",
              desc: "rpmNo"
            },
            rules: [
              {
                required: true,
                message: "请选择设备型号",
                trigger: "blur",
              },
            ],
          },
          {
            label: "设备型号",
            prop: "rpmName",
            type: "input",
            rules: [
              {
                required: true,
                message: "请输入设备型号",
                trigger: "blur",
              },
            ],
          },
          {
            label: "设备编号",
            prop: "rsSn",
            type: "input",
            width: 150,
            search: true,
            searchOrder: 9,
            rules: [
              {
                required: true,
                message: "请输入设备编号",
                trigger: "blur",
              },
            ],
          },
          {
            label: "设备状态",
            prop: "isBind",
            type: "select",
            search: true,
            searchOrder: 22,
            dicUrl: "/api/blade-system/dict/dictionary?code=is_bind",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请选择设备状态",
                trigger: "blur",
              },
            ],
          },
          {
            label: "调拨状态",
            prop: "amount",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=amount_state",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            search: true,
            showColumn: false,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入调拨状态",
                trigger: "blur",
              },
            ],
          },
          {
            label: "活动类型",
            prop: "activeType",
            type: "select",
            search: true,
            searchOrder: 21,
            dicUrl: "/api/rb-oem/oem/active/active/list?current=-1&size=-1",
            props: {
              label: "activeName",
              value: "activeCode",
            },
            dicFormatter:(data)=>{
              return data.data.records
            },
            width:120,
            overHidden:true
          },
          {
            label: "活动名称",
            prop: "activeName",
            type: "input",
            width:140,
            overHidden:true
          },
          {
            label: "通道名称",
            prop: "aisleName",
            type: "input",
            rules: [
              {
                required: true,
                message: "请选择通道名称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "商户编号",
            searchLabel: "商户",
            prop: "rpiNo",
            type: 'select',
            minWidth: 140,
            overHidden:true,
            search: true,
            searchOrder: 7,
          },
          {
            label: "门头名称",
            prop: "rpiName",
            type: "input",
            minWidth: 180,
            overHidden:true,
            searchOrder: 11,
          },
          {
            label: "通道名称",
            prop: "aisleCode",
            type: "select",
            search: true,
            searchOrder: 12,
            dicUrl: "/api/rb-oem/oem/store/store/selectAisleList?current=-1&size=-1",
            props: {
              label: "aisleName",
              value: "aisleCode",
              desc: "aisleCode"
            },
            hide: true,
            overHidden:true,
            rules: [
              {
                required: true,
                message: "请选择通道名称",
                trigger: "blur",
              },
            ],
          },
          // {
          //   label: "音响密钥",
          //   prop: "yxToken",
          //   type: "input",
          //   searchOrder: 23,
          //   overHidden: true
          // },
          {
            label: "设备绑定日期",
            prop: "bindTime",
            type: "input",
            display: false,
            width: 140,
          },
          {
            label: "绑定台卡编号",
            prop: "qrCode",
            type: "input",
            display: false,
            width: 120,
            overHidden:true
          },
          {
            label: "绑定台卡日期",
            prop: "bindQrTime",
            type: "input",
            display: false,
            width: 140,
            overHidden:true
          },
          {
            label: "物联网卡编号",
            prop: "cardCode",
            type: "input",
            display: false,
            width: 120,
            overHidden:true
          },
          {
            label: "设备入库日期",
            prop: "createTime",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            width: 140,
            overHidden:true
          },
        //   {
        //     label: "绑定时间",
        //     prop: "rsBindTime",
        //     type: "input",
        //     search: true,
        //   },
        ],
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-oem/store/store/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.store_add, false),
        viewBtn: this.vaildData(this.permission.store_view, false),
        delBtn: this.vaildData(this.permission.store_delete, false),
        editBtn: this.vaildData(this.permission.store_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    getColor() {
      return state => {
        if (state == '0') {
          return '#F56C6C';
        } else if (state == '1') {
          return '#67C23A';
        }
      }
    },
    getColorStatus() {
      return state => {
        if (state == '0') {
          return '#E6A23C';
        } else if (state == '1') {
          return '#67C23A';
        }
      }
    }
  },
  methods: {
    /**
     * @func 入库
     * @desc 点击入库进入入库界面
     * */
    handleStorage() {
      this.$router.push({
        name: "库存入库",
        query: {
          rptNo:this.rptNo
        },
      });
    },
    /**
     * @func 调拨
     * @desc 点击调拨进入调拨界面
     * */
    handleAllot() {
      this.$router.push({
        name: "库存调拨",
        query: {
          e: this.$crypto.encrypt(JSON.stringify({
            rptNo: this.rptNo,
            stockType: 'sound'
          }))
        }
      });
    },
    /**
     * @func 回拨
     * @desc 点击回拨进入回拨界面
     * */
    handleRebate() {
      this.$router.push({
        name: "库存回拨",
        query: {
          rptNo:this.rptNo
        }
      });
    },
    /**
     * @func 设备管理
     * @desc 点击设备管理进入设备管理界面
     * @param {Object} row - 仓库信息
     * */
    handleDevice(row) {
      this.$router.push({
        name: "设备管理",
        query: {
          rpiNo: row.rpiNo
        }
      });
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    /* rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    }, */
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then((res) => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query,{rptNo: this.rptNo})
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&rptNo=${this.search.rptNo}`;
      exQuery += `&rpsNo=${this.search.rpsNo}`;
      exQuery += `&rpmNo=${this.search.rpmNo}`;
      exQuery += `&productType=${this.search.productType}`;
      exQuery += `&rsSn=${this.search.rsSn}`;
      exQuery += `&rpiNo=${this.search.rpiNo}`;
      exQuery += `&rsServiceNo=${this.search.rsServiceNo}`;
      exQuery += `&isBind=${this.search.isBind}`;
      exQuery += `&rsBindTime=${this.search.rsBindTime}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-oem/oem/store/store/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-oem/oem/store/store/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-tag--dark.el-tag--success {
  border-color: transparent;
  opacity: 0.8;
}
</style>
